package collector.support;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.Semaphore;

public class URLHandler {
	private Semaphore contentSem;
	private String content;
	private URL url;

	public static URLHandler create(String url) {
		try {
			return new URLHandler(new URL(url));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return null;
	}

	private URLHandler(URL url) {
		contentSem = new Semaphore(1);
		try {
			contentSem.acquire();
			this.url = url;
			new DownloaderThread().start();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public class DownloaderThread extends Thread {
		public void run() {
			// store content
			// Download
			do {
				try {
					HttpURLConnection connection = (HttpURLConnection) url
							.openConnection();
					connection.setConnectTimeout(10000);
					connection.connect();
					BufferedReader rd = new BufferedReader(new InputStreamReader(connection
							.getInputStream(),"ISO-8859-1"));
					StringBuilder sb = new StringBuilder();

					String line = "";
					while ((line = rd.readLine()) != null) {
						sb.append(line);
					}
					content = sb.toString();
					//System.out.println(content);
					break;
				} catch (IOException e) {
					e.printStackTrace();
				}
			} while (true);
			// release semaphore
			contentSem.release();
		}
	}

	public String getContent() {
		// Wait for download to complete
		try {
			contentSem.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		String theContent = this.content;
		contentSem.release();

		// return content
		return theContent;
	}
}
